/*
 * @文件描述:
 * @公司: 山东大学信息学院
 * @作者: 李洪文
 * @Date: 2019-11-07 15:21:01
 * @LastEditors: 李洪文
 * @LastEditTime: 2019-11-07 15:24:25
 */

import AsyncStorage from '@react-native-community/async-storage';

export interface IUserInfo {
  realUsername: string;
  username: string;
  tenantCode: string;
}

const TOKEN_KEY = 'token';
const PERSON_CODE = 'personCode';
const USER_INFO = 'userInfo';
const PRIVILEGE = 'privilege';

export const saveToken = (token?: string) => {
  return AsyncStorage.setItem(TOKEN_KEY, token!);
};

export const savePersonCode = (personCode: string) => {
  AsyncStorage.setItem(PERSON_CODE, personCode);
};

export const getPersonCode = async () => {
  const result = await AsyncStorage.getItem(PERSON_CODE);
  return result || '';
};

export const saveUserInfo = (userInfo: IUserInfo) => {
  return AsyncStorage.setItem(USER_INFO, JSON.stringify(userInfo));
};

export const getUserInfo = async (): Promise<IUserInfo | undefined> => {
  const result = await AsyncStorage.getItem(USER_INFO);
  if (result) {
    return JSON.parse(result);
  }
  return undefined;
};

export const savePrivileges = (privileges: string[] = []) => {
  AsyncStorage.setItem(PRIVILEGE, JSON.stringify(privileges));
};

export const getPrivileges = async (): Promise<string[]> => {
  const result = await AsyncStorage.getItem(PRIVILEGE);
  if (result) {
    return JSON.parse(result);
  }
  return [];
};

/**
 * @功能描述: 退出登录
 * @参数:
 * @返回值:
 */
export const signOut = async () => {
  try {
    await Promise.all([
      AsyncStorage.removeItem(TOKEN_KEY),
      AsyncStorage.removeItem(USER_INFO),
      AsyncStorage.removeItem(PERSON_CODE),
    ]);
    return true;
  } catch (err) {
    return false;
  }
};

/**
 * @功能描述: 拿到token
 * @参数:
 * @返回值:
 */
export const getToken = async () => {
  const result = await AsyncStorage.getItem(TOKEN_KEY);
  return result || '';
};

/**
 * @功能描述: 判断是否已登录
 * @参数:
 * @返回值:
 */
export const isSignedIn = async () => {
  const result = await AsyncStorage.getItem(TOKEN_KEY);
  return !!result;
};
